package com.xyd.servlet;

import com.xyd.entity.Message;
import com.xyd.entity.User;
import com.xyd.service.UserService;
import com.xyd.service.impl.UserServiceImpl;
import com.xyd.util.JsonUtil;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 类描述：用户登录
 *
 * @author 张吉哲
 * @date 2021/1/9 13:50
 */
@WebServlet("/userLoginServlet")
public class UserLoginServlet extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String checkCodeServer = (String) request.getSession().getAttribute("CHECKCODE_SERVER");
    String veryCode = request.getParameter("veryCode");
    Message message = new Message();
    if (checkCodeServer.equalsIgnoreCase(veryCode)) {
      String username = request.getParameter("userName");
      String passWord = request.getParameter("passWord");
      UserService userService = new UserServiceImpl();
      User user = userService.loginUser(username, passWord);
      if (user == null) {
        message.setFlag(false);
        message.setMessage("用户名或密码错误");
      } else {
        message.setFlag(true);
        request.getSession().setAttribute("user", user);
      }
      JsonUtil.toJson(response, message);
      return;
    }

    message.setFlag(false);
    message.setMessage("验证码错误");
    JsonUtil.toJson(response, message);
  }

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doPost(request, response);
  }
}
